(function($) {
    $.fn.editableimage = function(previewUrl) {
        this.each(function() {
            var $el = $(this);
            var source = $el.attr('src');
            var name = $el.attr('name');
            
            var i = source.search('base64,');
            if(i < 0) {
                console.log('Cannot make editable image of something else but data URLs');
                return;
            }
            var base64Data = source.substring(i+7);
            
            $el.wrap('<div class="editable_img_wrap"></div>');
            $el = $el.parent();
            
            var editBtn = $('<br /><a class="image-edit">Edit</a>');
            $el.append(editBtn);
            
            $el.append('<input type="hidden" value="'+base64Data+'" name="'+name+'" />');
            
            editBtn.click(function() {
                var $editBtn = $(this);
                $editBtn.hide();
                var inputFile = $('<input type="file" name="file" />');
                $el.append($('<form style="display: none;" action="'+previewUrl+'" method="POST" enctype="multipart/form-data"></form>').append(inputFile));
                
                var iframeId = 'editableimage_hiddenframe_'+(Math.floor(Math.random()*10));
                var iframe = $('<iframe style="display: none;" id="'+iframeId+'"></iframe>');
                $el.append(iframe);
                iframe.load(function() {
                    $(this).parent().find('form').hide();
                    var json = $(this).contents().text();
                    var data = JSON.parse(json);
                    
                    if(data.length < 1) {
                        console.log('Error retrieving base64 data');
                    } else {
                        $(this).parent().find('form').remove();
                        $editBtn.show();
                        $(this).parent().find('input').val(data[0]);
                        $(this).parent().find('img').attr('src', 'data:image/png;base64,'+data[0]);
                    }
                });
                inputFile.change(function() {
                    $(this).parent().attr('target', iframeId).submit();
                }).parent().show(); 
            });
        });
        
        return this;
    };
})(jQuery);
